import pymysql

from utils.log_util import logger
from utils.read import base_data

data = base_data.read_ini()['mysql']
DB_CONF = {
    'host': data['MYSQL_HOST'],
    'port': int(data['MYSQL_PORT']),
    'user': data['MYSQL_USER'],
    'password': data['MYSQL_PASSWORD'],
    'database': data['MYSQL_DB']
}


class MysqlDb:
    # mysql连接
    def __init__(self, host, user, password, database, port=3306):
        self.conn = pymysql.connect(**DB_CONF, autocommit=True)
        self.cur = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
        print("数据库连接成功")

    # 释放资源
    def __del__(self):
        self.cur.close()
        self.conn.close()

    # mysql查询1条
    def select_db_one(self, sql):
        logger.info(f'执行sql:{sql}')
        self.cur.execute(sql)
        return self.cur.fetchone()

    # mysql查询多条
    def select_db(self, sql):
        logger.info(f'执行sql:{sql}')
        self.cur.execute(sql)
        return self.cur.fetchall()

    def excute_db(self, sql):
        try:
            logger.info(f'执行sql:{sql}')
            self.cur.execute(sql)
            self.conn.commit()
        except Exception as e:
            logger.error("执行sql出错{}".format(e))
            return self.cur.fetchall()


db = MysqlDb(**DB_CONF)
if __name__ == '__main__':
    result = db.select_db_one("SELECT game_product_id, state, ranking FROM ys_base_db.game_product limit 1;")
    print(result)
    # #mysql插入
    # def insert(self, sql):
    #     self.cur.execute(sql)
    #     self.conn.commit()
    #     return self.cur.lastrowid

    # #mysql更新
    # def update(self, sql):
    #     self.cur.execute(sql)
    #     self.conn.commit()
    #     return self.cur.rowcount
    # #mysql删除
    # def delete(self, sql):
    #     self.cur.execute(sql)
    #     self.conn.commit()
    #     return self.cur.rowcount
